<template>
  <div class="app-container">

    <YxhyTableQuery :query-params.sync="queryParams" :query-columns="queryColumns" @search="handleQuery" />

    <YxhyTableData :columns="columns" :data="tableList" :loading="loading">
      <!-- 账号插槽 -->
      <template #username>
        <el-table-column align="center">
          <template
            slot="header"
            slot-scope="{ column, $index }"
          >
            <p class="font-color-th">账号</p>
            <p class="font-color-th">密码</p>
          </template>
          <template slot-scope="{ row }">
            <p class="font-color-td">{{ row.username | domEmpty }}</p>
            <p class="font-color-td">{{ row.password | domEmpty }}</p>
          </template>
        </el-table-column>
      </template>
      <!-- 插槽内容 -->
      <template #action>
        <el-table-column label="操作" width="80">
          <template slot-scope="scope">
            <div class="table-action-panel">
<!--              <el-button type="success" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>-->
              <template v-if="scope.row.status === 1">
                <el-button type="danger" size="mini" @click="handleUpdateFlag(scope.row)">禁用</el-button>
              </template>
              <template v-else-if="scope.row.status === 2">
                <el-button type="primary" size="mini" @click="handleUpdateFlag(scope.row)">启用</el-button>
              </template>
            </div>
          </template>
        </el-table-column>
      </template>
    </YxhyTableData>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryPage.pageNum"
      :limit.sync="queryPage.limit"
      @pagination="init"
    />

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="600px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="140px">
        <el-form-item label="账户状态" prop="status">
          <el-switch v-model="form.status" />
        </el-form-item>
        <el-form-item label="投手名称" prop="chinese_name">
          <el-input v-model="form.chinese_name" placeholder="请输入投手名称" />
        </el-form-item>
        <el-form-item label="账号" prop="username">
          <el-input v-model="form.username" placeholder="请输入账号" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="备注" prop="note">
          <el-input v-model="form.note" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { columnsSelectMp, columnsStatic, LEVEL_LEVEL, STATUS } from './Ds.js'
import { queryLevelAll } from '@/api/distribute/level'
import {
  addDistUser,
  editDistUser,
  editDistUserStatus,
  queryDistUserDetail
} from '@/api/distribute/distAccount'
import { queryListMp, queryListNonSortMp } from '@/api/miniProgram/mp'
import { queryDistUserSeed } from '@/api/distribute/seedAccount'

export default {
  name: 'SeedAccountList',
  data() {
    return {
      // 总条数
      total: 0,
      // 表格数据
      tableList: [],
      // 分页参数
      queryPage: {
        pageNum: 1,
        limit: 10
      },
      // 查询参数
      queryParams: {
        id: undefined,
        company: undefined,
        dist_level_id: undefined
      },
      // 查询表单
      queryColumns: [
        {
          label: '',
          placeholder: '请输入投手ID',
          type: 'input',
          param: 'id'
        }],
      loading: false,
      // 表格列
      columns: columnsStatic,
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {
        status: 1, // 1-正常，2-禁用
        chinese_name: undefined,
        company: undefined,
        social_credit_code: undefined,
        dist_level_id: undefined,
        dd_into_rate: undefined, // 仅前端显示
        order_rate: undefined, // 仅前端显示
        tax_rate: undefined,
        product_ids: undefined,
        auth_start_time: undefined,
        auth_end_time: undefined,
        contact_person: undefined,
        contact_mobile: undefined,
        contact_wechat: undefined,
        note: undefined,
        role: 'main'// main分销商 seed投手
      },
      formDetail: {},
      // 表单校验
      rules: {
        company: [
          { required: true, message: '请输入公司主体', trigger: ['blur', 'change'] }
        ],
        social_credit_code: [
          { required: true, message: '请输入统一社会信用代码', trigger: ['blur', 'change'] }
        ],
        dist_level_id: [
          { required: true, message: '请选择分销等级', trigger: ['blur', 'change'] }
        ],
        tax_rate: [
          { required: true, message: '请输入税率', trigger: ['blur', 'change'] }
        ],
        product_ids: [
          { required: true, message: '请选择授权小程序', trigger: ['blur', 'change'] }
        ],
        auth_start_time: [
          {
            validator: (rule, value, callback) => {
              if (!value || !this.form.auth_end_time) return callback(new Error('请选择授权日期'))
              else callback()
            },
            trigger: ['blur', 'change']
          }
        ]
      },

      // 分销等级下拉框数据源
      levelColumns: [],
      // 关联小程序
      queryParamsSelectMp: {
        product_id_search: undefined,
        product_name_search: undefined
      },
      queryColumnsSelectMp: [
        {
          label: '',
          placeholder: '请输入id',
          type: 'input',
          param: 'product_id_search'
        }, {
          label: '',
          placeholder: '请输入小程序名称',
          type: 'input',
          param: 'product_name_search'
        }
      ],
      columnsSelectMp,
      queryListMp,
      queryListNonSortMp,
      queryLevelAll
    }
  },
  computed: {
    isEdit() {
      return ![undefined, ''].includes(this.form.id)
    }
  },
  created() {
    this.init()
  },
  methods: {
    async init() {
      this.loading = true
      const res = await queryDistUserSeed({
        ...this.queryPage,
        ...this.queryParams
      })
      res.data.map(e => {
        const { status, dist_level_id } = e
        e.status_text = STATUS[status]

        if (dist_level_id) {
          // 投手账号没有dist_level_id
          const { dd_into_rate, level } = this.levelColumns.find(levelItem => levelItem.id === dist_level_id)
          e.level_text = level
          e.dd_into_rate_text = `${dd_into_rate}%`
        } else {
          e.company = '-'
          e.level_text = '-'
          e.dd_into_rate_text = '-'
        }
      })
      this.tableList = res.data
      this.total = res.total
      this.loading = false
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        status: 1, // 1-正常，2-禁用
        company: undefined,
        social_credit_code: undefined,
        dist_level_id: undefined,
        dd_into_rate: undefined, // 仅前端显示
        order_rate: undefined, // 仅前端显示
        tax_rate: undefined,
        product_ids: undefined,
        auth_start_time: undefined,
        auth_end_time: undefined,
        contact_person: undefined,
        contact_mobile: undefined,
        contact_wechat: undefined,
        note: undefined,
        role: 'main'// main分销商 seed投手
      }
      this.resetForm('formRef')
    },
    onChangeLevel(id) {
      const item = this.levelColumns.find(e => e.id === id)
      const { dd_into_rate, order_rate } = item
      this.form.dd_into_rate = dd_into_rate
      this.form.order_rate = order_rate
    },
    /** 接收小程序选择 */
    handleSelectResultMp(rows) {
      const is_arr = rows.map(item => item.product_id)
      this.form.product_ids = is_arr
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryPage.pageNum = 1
      this.init()
    },
    /** 清空搜索按钮操作 */
    handleClear() {
      this.init()
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加分销商账户'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const { id } = row
      this.reset()

      this.open = true
      this.title = '修改分销商账户'
      queryDistUserDetail({
        id
      }).then(res => {
        const data = res[0]
        let product_ids__ = []
        let auth_start_time__ = ''
        let auth_end_time__ = ''

        if (data.products.length > 0) {
          product_ids__ = data.products.map(e => e.product_id)
          const { auth_start_time, auth_end_time } = data.products[0]
          auth_start_time__ = auth_start_time
          auth_end_time__ = auth_end_time
        }

        const transData = {
          ...data,
          company: data.username,
          product_ids: product_ids__,
          auth_start_time: auth_start_time__,
          auth_end_time: auth_end_time__
        }
        this.form = JSON.parse(JSON.stringify(transData))
        this.formDetail = JSON.parse(JSON.stringify(transData))
      })
    },
    /** 启用/禁用按钮操作 */
    async handleUpdateFlag(row) {
      const { id, status } = row
      const transStatus = status === 1 ? 2 : 1
      const confirmTitle = status === 1 ? '确认禁用吗？' : '确认启用吗?'

      this.$modal.confirm(confirmTitle).then(function() {
      }).then(() => {
        editDistUserStatus({
          id,
          status: transStatus
        }).then(() => {
          row.status = transStatus
          row.status_text = STATUS[transStatus]
          this.$modal.msgSuccess('操作成功')
        })
      }).catch(() => {})
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['formRef'].validate((valid) => {
        if (valid) {
          const is_str = this.form.product_ids.toString()
          // 后端有意思的格式要求："[1,2]"  字符串伪数组
          this.form.product_ids = `[${is_str}]`
          if (this.form.id != undefined) {
            editDistUser(this.form).then(res => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.init()
            })
          } else {
            addDistUser(this.form).then(res => {
              this.$modal.msgSuccess('添加成功')
              this.open = false
              this.init()
            })
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
